import time
import ddddocr
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

class Base:
    def __init__(self,driver):
        self.driver = driver

    def open_url(self,url):
        self.driver.get(url)

    def open_browser(self, browser_type):
        if browser_type.lower() == "Chrome":
            self.driver = webdriver.Chrome()
        elif browser_type.lower() == "firefox":
            self.driver = webdriver.Firefox()
        elif browser_type.lower() == "Edge":
            self.driver = webdriver.Edge()
        else:
            print('浏览器不兼容')

    def find_element(self,loc):
        try:
            WebDriverWait(self.driver, 20, 0.5).until(lambda driver: self.driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as q:
            t = time.strftime('%Y%m%d%H%M%S',time.localtime())
            self.driver.save_screenshot(t + '.png')
            print(q)

    def click(self,loc):
        self.find_element(loc).click()

    def send_keys(self,loc,info):
        self.find_element(loc).send_keys(info)

    def text(self,loc):
        return self.find_element(loc).text

    def ddddocr(self,loc,loc2):
        ocr = ddddocr.DdddOcr()
        code_element = self.find_element(loc)
        code_screenshot = code_element.screenshot_as_png
        code = ocr.classification(code_screenshot)
        print(f'识别到验证码:{code}')
        self.find_element(loc2).send_keys(code)

    def find_elements(self,loc):
        try:
            for i in self.driver.find_elements(*loc):
                return print(i.text)
        except Exception as e:
            print(e)